package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.pojo.DishFlavor;
import com.reggie.service.DishFlavorService;
import com.reggie.utils.Result;
import com.reggie.dto.DishDto;
import com.reggie.pojo.Category;
import com.reggie.pojo.Dish;
import com.reggie.service.CategoryService;
import com.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加新菜品，并且保存口味
     * @param dishDto 前端传回数据，包含口味信息
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return Result.success("新增菜品成功");
    }

    /**
     * 检查菜品是否重复
     * @param name
     * @return
     */
    @GetMapping("/check/{name}")
    public Result<String> check(@PathVariable String name) {
        //查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(name != null, Dish::getName, name);

        Dish dish = dishService.getOne(wrapper);
        if (dish != null) {
            return Result.error("菜品已存在");
        }
        return Result.success("菜品未重复");
    }

    /**
     * 菜品分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<DishDto>> page(int page, int pageSize, String name) {
        //构造分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Dish::getName, name);
        wrapper.orderByAsc(Dish::getCategoryId).orderByDesc(Dish::getCreateTime);
        //分页查询,查询完成之后自动回填到dishPage对象中
        dishService.page(dishPage, wrapper);

        //对象拷贝,首先将普通属性拷贝到dishDtoPage中
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //接下来使用stream流对records属性进行操作
        List<Dish> records = dishPage.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            //item都是Dish对象的格式，在创建一个dishDto对象
            DishDto dishDto = new DishDto();
            //由于对象是新建的没有其他数据所以先把原来的数据copy到新对象上
            BeanUtils.copyProperties(item, dishDto);
            //根据categoryID查询分类名称赋给dishDto对象
            Category category = categoryService.getById(item.getCategoryId());

            //保险起见，不为空时再赋值
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            //不要忘记将对象返回
            return dishDto;
        }).collect(Collectors.toList());

        //最后将刚刚省略的recodes属性赋值
        dishDtoPage.setRecords(list);

        return Result.success(dishDtoPage);
    }

    /**
     * 根据id获取菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> getById(@PathVariable String id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     * 更新菜品信息和口味信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return Result.success("更新菜品成功");
    }

    /**
     * 更改菜品状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable int status,@RequestParam List<Long> ids) {
        //遍历数组，完成状态设置
        for (Long id : ids) {
            //修改状态
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            //状态存入
            dishService.updateById(dish);
        }
        if (status == 0) {
            return Result.success("停售成功");
        }
        return Result.success("起售成功");
    }

    /**
     * 删除菜品和菜品口味数据
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(@RequestParam List<Long> ids) {
        dishService.deleteWithFlavor(ids);
        return Result.success("已删除菜品");
    }

    /**
     * 根据菜品属性，查询菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")    //参数用dish对象接收，如果有其他数据传入也可以接收
    public Result<List<DishDto>> list(Dish dish) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //指定只查询起售状态的菜品
        wrapper.eq(Dish::getStatus, 1);
        //添加排序规则
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);

        List<Dish> list = dishService.list(wrapper);

        List<DishDto> dishDtoList = dishService.getDishDto(list);

        return Result.success(dishDtoList);
    }

}
